package com.gk.study.controller;

import com.gk.study.common.APIResponse;
import com.gk.study.common.ResponeCode;
import com.gk.study.entity.Tag;
import com.gk.study.entity.Thing;
import com.gk.study.permission.Access;
import com.gk.study.permission.AccessLevel;
import com.gk.study.service.TagService;
import com.gk.study.service.ThingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.alibaba.fastjson.JSON;

@RestController
@RequestMapping("/thing")
public class ThingController {

    private final static Logger logger = LoggerFactory.getLogger(ThingController.class);

    @Autowired
    ThingService service;
    @Autowired
    TagService tagService;

    @Value("${File.uploadPath}")
    private String uploadPath;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public APIResponse list(String keyword, String sort, String c, String tag){
        List<Thing> list =  service.getThingList(keyword, sort, c, tag);

        return new APIResponse(ResponeCode.SUCCESS, "查询成功", list);
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public APIResponse detail(String id){
        Thing thing =  service.getThingById(id);

        return new APIResponse(ResponeCode.SUCCESS, "查询成功", thing);
    }

    @Access(level = AccessLevel.ADMIN)
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @Transactional
    public APIResponse create(Thing thing) throws IOException {
        String url = saveThing(thing);
        if(!StringUtils.isEmpty(url)) {
            thing.cover = url;
        }

        service.createThing(thing);
        return new APIResponse(ResponeCode.SUCCESS, "创建成功");
    }

    @Access(level = AccessLevel.ADMIN)
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public APIResponse delete(String ids){
        System.out.println("ids===" + ids);
        // 批量删除
        String[] arr = ids.split(",");
        for (String id : arr) {
            service.deleteThing(id);
        }
        return new APIResponse(ResponeCode.SUCCESS, "删除成功");
    }

    @Access(level = AccessLevel.ADMIN)
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @Transactional
    public APIResponse update(Thing thing) throws IOException {
        System.out.println(thing);
        String url = saveThing(thing);
        if(!StringUtils.isEmpty(url)) {
            thing.cover = url;
        }

        service.updateThing(thing);
        return new APIResponse(ResponeCode.SUCCESS, "更新成功");
    }

    public String saveThing(Thing thing) throws IOException {
        MultipartFile file = thing.getImageFile();
        String newFileName = null;
        if(file !=null && !file.isEmpty()) {

            // 存文件
            String oldFileName = file.getOriginalFilename();
            String randomStr = UUID.randomUUID().toString();
            newFileName = randomStr + oldFileName.substring(oldFileName.lastIndexOf("."));
            String filePath = uploadPath + File.separator + "image" + File.separator + newFileName;
            File destFile = new File(filePath);
            if(!destFile.getParentFile().exists()){
                destFile.getParentFile().mkdirs();
            }
            file.transferTo(destFile);
        }
        if(!StringUtils.isEmpty(newFileName)) {
            thing.cover = newFileName;
        }
        if(!StringUtils.isEmpty(thing.getCourseName())) {
            // 确保courseName被保存
            // MyBatis-Plus会自动映射到数据库的course_name列
        }
        return newFileName;
    }

    @RequestMapping(value = "/listUserThing", method = RequestMethod.GET)
    public APIResponse listUserThing(String userId){
        List<Thing> list =  service.getUserThing(userId);

        return new APIResponse(ResponeCode.SUCCESS, "查询成功", list);
    }

    @Access(level = AccessLevel.LOGIN)
    @RequestMapping(value = "/getUserThingByUserId", method = RequestMethod.GET)
    public APIResponse getUserThingByUserId(@RequestParam String userId) {
        Thing thing = service.getThingByUserId(userId);
        return new APIResponse(ResponeCode.SUCCESS, "查询成功", thing);
    }

    @Access(level = AccessLevel.LOGIN)
    @RequestMapping(value = "/updateUserThing", method = RequestMethod.POST)
    @Transactional
    public APIResponse updateUserThing(@RequestParam(required = false) MultipartFile imageFile,
                                       @RequestParam Map<String, String> params) throws IOException {
        // 验证当前用户权限
        Thing existingThing = service.getThingByUserId(params.get("userId"));
        if(existingThing == null) {
            return new APIResponse(ResponeCode.FAIL, "用户信息不存在");
        }

        // 绑定新数据
        Thing thing = new Thing();
        BeanUtils.copyProperties(existingThing, thing); // 复制原有数据

        thing.setTitle(params.get("title"));
        thing.setSex(params.get("sex"));
        thing.setAge(params.get("age")); // 类型需匹配数据库
        thing.setLocation(params.get("location"));
        thing.setMobile(params.get("mobile"));
        thing.setPrice(params.get("price")); // 类型需匹配
        thing.setDescription(params.get("description"));

        // 处理分类ID
        if (params.containsKey("classificationId")) {
            thing.setClassificationId(Long.valueOf(params.get("classificationId")));
        }

        if (params.containsKey("tags")) {
            List<Long> tags = JSON.parseArray(params.get("tags"), Long.class);
            thing.setTags(tags);

            // 设置course_name
            if (!tags.isEmpty()) {
                Tag tag = tagService.getTagById(String.valueOf(tags.get(0)));
                if (tag != null) {
                    thing.setCourseName(tag.getTitle());
                }
            }
        }

        // 处理辅导科目：根据tag设置courseName
        if (thing.getTags() != null && !thing.getTags().isEmpty()) {
            Long tagId = thing.getTags().get(0);
            Tag tag = tagService.getTagById(String.valueOf(tagId));
            if (tag != null) {
                thing.setCourseName(tag.getTitle()); // 将tag标题存入course_name
            } else {
                thing.setCourseName(existingThing.getCourseName());
            }
        } else {
            thing.setCourseName(existingThing.getCourseName());
        }

        // 保留原有未修改字段
        if (StringUtils.isEmpty(thing.getTitle())) {
            thing.setTitle(existingThing.getTitle());
        }
        if (StringUtils.isEmpty(thing.getDescription())) {
            thing.setDescription(existingThing.getDescription());
        }
        if (StringUtils.isEmpty(thing.getPrice())) {
            thing.setPrice(existingThing.getPrice());
        }
        if (StringUtils.isEmpty(thing.getMobile())) {
            thing.setMobile(existingThing.getMobile());
        }
        if (StringUtils.isEmpty(thing.getAge())) {
            thing.setAge(existingThing.getAge());
        }
        if (StringUtils.isEmpty(thing.getSex())) {
            thing.setSex(existingThing.getSex());
        }
        if (StringUtils.isEmpty(thing.getLocation())) {
            thing.setLocation(existingThing.getLocation());
        }
//        if (StringUtils.isEmpty(thing.getCourseName())) {
//            thing.setCourseName(existingThing.getCourseName());
//        }
        if (StringUtils.isEmpty(thing.getClassificationId())) {
            thing.setClassificationId(existingThing.getClassificationId());
        }
        if (StringUtils.isEmpty(thing.getStatus())) {
            thing.setStatus(existingThing.getStatus());
        }
        if (StringUtils.isEmpty(thing.getCreateTime())) {
            thing.setCreateTime(existingThing.getCreateTime());
        }
        if (StringUtils.isEmpty(thing.getPv())) {
            thing.setPv(existingThing.getPv());
        }
        if (StringUtils.isEmpty(thing.getRecommendCount())) {
            thing.setRecommendCount(existingThing.getRecommendCount());
        }
        if (StringUtils.isEmpty(thing.getWishCount())) {
            thing.setWishCount(existingThing.getWishCount());
        }
        if (StringUtils.isEmpty(thing.getCollectCount())) {
            thing.setCollectCount(existingThing.getCollectCount());
        }
        if (thing.getTags() == null || thing.getTags().isEmpty()) {
            thing.setTags(existingThing.getTags());
        }

        // 处理封面图片
//        String url = saveThing(thing);
        if (imageFile != null && !imageFile.isEmpty()) {
            thing.setImageFile(imageFile);
            String url = saveThing(thing);
            thing.setCover(url);
        }
        thing.setId(existingThing.getId()); // 设置主键用于更新
        service.updateThing(thing);
        return new APIResponse(ResponeCode.SUCCESS, "更新成功");
    }

}
